/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：用于实现UI的颜色渐变效果
* CreateTime：2021-01-14 15:18:07
* Version：1.0
* Modify Recorder：
*************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace TinyToolKit
{
    [AddComponentMenu("UI/Effects/Gradient", 10)]
    public class UIGradient : BaseMeshEffect
    {
        public Gradient gradient;
        [Range(-1f, 1f)] public float Offset;
        [Range(0, 360f)] public int angle;
        
        private List<UIVertex> _vertexList = new List<UIVertex>();

        public override void ModifyMesh(VertexHelper helper)
        {
            if (!IsActive() || helper.currentVertCount == 0) return;

            _vertexList.Clear();
            //把当前的顶点信息保存到_vertexList中
            helper.GetUIVertexStream(_vertexList);
            
            float x = Mathf.Cos(angle * Mathf.Deg2Rad);
            float y = Mathf.Sin(angle * Mathf.Deg2Rad);
            Vector2 dir = new Vector2(x,y);

            UIVertex vertex = new UIVertex();
            for (int i = 0; i < helper.currentVertCount; i++)
            {
                helper.PopulateUIVertex(ref vertex, i);
                float value = Vector2.Dot(dir.normalized, vertex.position.normalized) * 0.5f + 0.5f;

                if (gradient != null)
                    vertex.color = gradient.Evaluate(Offset + value);
                helper.SetUIVertex(vertex, i);
            }
        }
    }
}